package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.OrdersMapper;
import com.sky.result.PageResult;
import com.sky.service.*;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static org.apache.commons.lang3.ObjectUtils.min;

/**
 * 订单表 服务实现类
 *
 * @author alkaid
 * @since 2024-02-25
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        // 获取当前用户 id
        Long userId = BaseContext.getCurrentId();

        // 1. 处理异常情况，地址、购物车是否正常

        // 1.1 查询用户地址
        AddressBook addressBook = addressBookService.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            // 地址为空，下单失败，抛出异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 1.2 查询用户购物车
        List<ShoppingCart> shoppingCartList = shoppingCartService.showShoppingCart(userId);
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            // 购物车为空，不能下单
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 2. 向订单表插入单条数据
        Orders orders = new Orders();
        // 2.1 属性拷贝
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        // 2.2 填充数据
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);
        orders.setUserName(userService.getById(userId).getName());
//        orders.setAddress(String.valueOf(addressBook));

        // 2.3 插入数据
        ordersMapper.insert(orders);
        // 获取插入后的数据 id
        Long orderId = orders.getId();

        // 3. 向订单明细表插入多条详细数据
        // 遍历购物车数据，逐个封装插入
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            // 设置关联订单 id
            orderDetail.setOrderId(orderId);
            // 放入列表
            orderDetailList.add(orderDetail);
        }
        // 批量插入
        orderDetailService.saveBatch(orderDetailList);

        // 4. 清空用户购物车
        shoppingCartService.clearShoppingCart(userId);

        // 5. 封装返回结果
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();

    }

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        Long userId = BaseContext.getCurrentId();
        User user = userService.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal("0.01"), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );

        // 空
        JSONObject jsonObject = new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    @Override
    public void paySuccess(String outTradeNo) {
        Orders order = this.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(order.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.updateById(orders);

        // 向浏览器推送支付成功消息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 1);
        jsonObject.put("orderId", orders.getId());
        jsonObject.put("content", "订单号：" + outTradeNo);

        webSocketServer.sendToAllClient(jsonObject.toJSONString());

    }

    @Override
    public Orders getByNumber(String outTradeNo) {
        return ordersMapper.selectOne(
                new LambdaQueryWrapper<Orders>()
                        .eq(Orders::getNumber, outTradeNo)
        );
    }

    @Override
    public PageResult pageQueryByStatus(int pageNum, int pageSize, Integer status) {
        // 获取用户 id
        Long userId = BaseContext.getCurrentId();

        // 查询用户订单信息
        // 查询全部订单信息
        List<Orders> ordersAllList = ordersMapper.selectList(
                new LambdaQueryWrapper<Orders>()
                        .eq(Orders::getUserId, userId)
                        .eq(status != null, Orders::getStatus, status)
        );

        if (ordersAllList == null || ordersAllList.isEmpty()) {
            return new PageResult(0, null);
        }

        // 手动分页
        // 左端 = （页数 - 1）* 每页条数
        int l = (pageNum - 1) * pageSize;

        // 左端起点超出起点
        if (l >= ordersAllList.size()) {
            return new PageResult(0, null);
        }

        // 右端 = 左端 +
        int r = l + pageSize;
        r = min(r, ordersAllList.size());
        // 当前分页下的数据
        // TODO 分页查询失败，需要修改
        List<Orders> ordersNowList = ordersAllList.subList(l, r);

        // 保存返回数据
        List<OrderVO> orderVOList = new ArrayList<>();

        // 查询订单详细信息并封装
        for (Orders orders : ordersNowList) {
            Long orderId = orders.getId();

            // 查询订单详细信息
            List<OrderDetail> orderDetailList = orderDetailService.getByOrderId(orderId);

            // 拷贝数据
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDetailList(orderDetailList);

            // 存入列表
            orderVOList.add(orderVO);
        }

        // 返回数据


        return new PageResult(orderVOList.size(), orderVOList);
    }

    @Override
    public OrderVO getDetailsById(Long id) {
        Orders orders = ordersMapper.selectById(id);

        // 查询套餐明细
        List<OrderDetail> orderDetailList = orderDetailService.getByOrderId(id);

        // 封装数据
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    @Override
    public void userCancelById(Long id) {
        // 查询订单
        Orders orders = ordersMapper.selectById(id);

        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            // 退款

            // 修改支付状态
            orders.setPayStatus(Orders.REFUND);
        }

        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.updateById(orders);

    }

    @Override
    public void repetitionById(Long id) {
        // 查询订单
        Long userId = BaseContext.getCurrentId();

        // 查询订单详情
        List<OrderDetail> orderDetailList = orderDetailService.getByOrderId(id);

        // 将订单详情转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        shoppingCartService.saveBatch(shoppingCartList);

    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        int pageNum = ordersPageQueryDTO.getPage();
        int pageSize = ordersPageQueryDTO.getPageSize();

        // 查询符合条件的订单信息
        List<Orders> orderAllList = ordersMapper.selectList(
                new LambdaQueryWrapper<Orders>()
                        .like(ordersPageQueryDTO.getNumber() != null, Orders::getNumber, ordersPageQueryDTO.getNumber())
                        .like(ordersPageQueryDTO.getPhone() != null, Orders::getPhone, ordersPageQueryDTO.getPhone())
                        .eq(ordersPageQueryDTO.getStatus() != null, Orders::getStatus, ordersPageQueryDTO.getStatus())
                        .eq(ordersPageQueryDTO.getUserId() != null, Orders::getUserId, ordersPageQueryDTO.getUserId())
                        .ge(ordersPageQueryDTO.getBeginTime() != null, Orders::getOrderTime, ordersPageQueryDTO.getBeginTime())
                        .le(ordersPageQueryDTO.getEndTime() != null, Orders::getOrderTime, ordersPageQueryDTO.getEndTime())
        );

//        if (orderAllList == null || orderAllList.isEmpty()) {
//            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
//        }


        // 手动分页
        // 左端 = （页数 - 1）* 每页条数
        int l = (pageNum - 1) * pageSize;

        // 左端起点超出起点
        if (l >= orderAllList.size()) {
            return new PageResult(0, null);
        }

        // 右端 = 左端 +
        int r = l + pageSize;
        r = min(r, orderAllList.size());

        List<Orders> orderList = orderAllList.subList(l, r);

        List<OrderVO> orderVOList = getOrderVOList(orderList);

        return new PageResult(orderVOList.size(), orderVOList);
    }

    @Override
    public OrderStatisticsVO getStatistics() {
        Integer toBeConfirmedNum = Math.toIntExact(countStatus(Orders.TO_BE_CONFIRMED));
        Integer confirmedNum = Math.toIntExact(countStatus(Orders.CONFIRMED));
        Integer deliveryInProgressNum = Math.toIntExact(countStatus(Orders.DELIVERY_IN_PROGRESS));

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        orderStatisticsVO.setToBeConfirmed(toBeConfirmedNum);
        orderStatisticsVO.setConfirmed(confirmedNum);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgressNum);

        return orderStatisticsVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Long orderId = ordersConfirmDTO.getId();

        Orders order = getById(orderId);
        order.setStatus(Orders.CONFIRMED);

        ordersMapper.updateById(order);

    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 查询订单
        Orders order = getById(ordersRejectionDTO);

        // 检验订单状态
        if (order == null || !Objects.equals(order.getStatus(), Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 检验支付状态
        Integer payStatus = order.getPayStatus();
        if (Objects.equals(payStatus, Orders.PAID)) {
            // 退款
        }

        // 更新数据
        order.setStatus(Orders.CANCELLED);
        order.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        order.setCancelTime(LocalDateTime.now());

        ordersMapper.updateById(order);

    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据 id 查询订单
        Orders order = getById(ordersCancelDTO.getId());

        // 检验支付状态
        Integer payStatus = order.getPayStatus();
        if (Objects.equals(payStatus, Orders.PAID)) {
            // 退款
        }

        // 更新数据
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason(ordersCancelDTO.getCancelReason());
        order.setCancelTime(LocalDateTime.now());

        ordersMapper.updateById(order);


    }

    @Override
    public void delivery(Long id) {
        // 查询订单
        Orders order = getById(id);

        // 校验订单状态
        if (order == null || !Objects.equals(order.getStatus(), Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersMapper.updateById(order);

    }

    @Override
    public void complete(Long id) {
        // 查询订单
        Orders order = getById(id);

        // 检验订单状态
        if (order == null || !Objects.equals(order.getStatus(), Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 更新数据
        order.setStatus(Orders.COMPLETED);
        order.setDeliveryTime(LocalDateTime.now());

        ordersMapper.updateById(order);
    }

    @Override
    public List<Orders> queryByStatusAndTime(Integer status, LocalDateTime timeNow) {

        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<Orders>()
                .eq(status != null, Orders::getStatus, status)
                .le(timeNow != null, Orders::getOrderTime, timeNow);

        return ordersMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public void reminder(Long id) {
        Orders order = getById(id);

        // 检验订单是否存在
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 向浏览器推送支付成功消息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 2);
        jsonObject.put("orderId", id);
        jsonObject.put("content", "订单号：" + order.getNumber());

        webSocketServer.sendToAllClient(jsonObject.toJSONString());

    }


    private List<OrderVO> getOrderVOList(List<Orders> orderList) {
        // 返回数据列表
        List<OrderVO> orderVOList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(orderList)) {
            for (Orders order : orderList) {
                // 单条数据
                OrderVO orderVO = new OrderVO();
                // 拷贝数据
                BeanUtils.copyProperties(order, orderVO);
                // 订单菜品字符串
                String orderDishes = getOrderDishesStr(order);

                // 填充数据
                orderVO.setOrderDishes(orderDishes);

                orderVOList.add(orderVO);
            }
        }

        return orderVOList;
    }


    /**
     * 将菜品信息转化为字符串返回
     *
     * @param order
     * @return
     */
    private String getOrderDishesStr(Orders order) {
        List<OrderDetail> orderDetailList = orderDetailService.getByOrderId(order.getId());

        List<String> orderDishStringList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        return String.join("", orderDishStringList);

    }

    private Long countStatus(Integer status) {
        return ordersMapper.selectCount(
                new LambdaQueryWrapper<Orders>()
                        .eq(Orders::getStatus, status)
        );
    }


}
